package com.wx.auth.servlet;

import com.wx.auth.utils.AuthUtil;
import net.sf.json.JSONObject;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.*;

/**
 * @Author: lijunwei
 * @Time: 2018/6/23 16:35
 */
@WebServlet("/callBack")
public class CallBackServlet extends HttpServlet {
    private String dbUrl;
    private String driverName;
    private String userName;
    private String passWord;
    private Connection conn = null;
    private PreparedStatement ps = null;
    private ResultSet rs = null;

//    @Override
////    public void init(ServletConfig config) throws ServletException {
////        try {
////            this.dbUrl = config.getInitParameter("dbUrl");
////            this.driverName = config.getInitParameter("driverName");
////            this.userName = config.getInitParameter("userName");
////            this.passWord = config.getInitParameter("passWord");
////            Class.forName(driverName);
////        } catch (ClassNotFoundException e) {
////            // TODO Auto-generated catch block
////            e.printStackTrace();
////        }
////    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        System.out.println("--------------@WebServlet(\"/callBack\")------------"+"2222");
        String code = req.getParameter("code");
        System.out.println("code============="+code);
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+ AuthUtil.APPID
                + "&secret="+AuthUtil.APPSECRET
                + "&code="+code
                + "&grant_type=authorization_code";
        System.out.println("url============="+url);
        JSONObject jsonObject = AuthUtil.doGetJson(url);
        System.out.println("jsonObject=======03======"+jsonObject.toString());
        String openid = jsonObject.getString("openid");
        String token = jsonObject.getString("access_token");
        System.out.println("openid=======token======"+openid+token);
        String infoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token="+token
                + "&openid="+openid
                + "&lang=zh_CN";
        JSONObject userInfo = AuthUtil.doGetJson(infoUrl);
        //--------输出用户信息-------------{
        // "openid":"oC2oN1M0cX7Pe3jyZ3AbHUy1aiTc",
        // "nickname":"李俊伟",
        // "sex":1,
        // "language":"zh_CN",
        // "city":"海淀",
        // "province":"北京",
        // "country":"中国",
        // "headimgurl":"http://thirdwx.qlogo.cn/mmopen/vi_32/DYAIOgq83eqXuHtq2wpHZEichRPvCGiaohiahIQeJJkLmRe6B4JNqxiaZPc8Rb99rIFyjL5rASd4YFgRqXOGP4Pjfg/132","
        // privilege":[]}
        System.out.println("--------输出用户信息-------------"+userInfo.toString());
        //String unionid = userInfo.getString("unionid");

        //1、使用微信用户信息直接登录，无需注册和绑定
        req.setAttribute("info", userInfo);
        req.getRequestDispatcher("/index1.jsp").forward(req, resp);

        //2、将微信与当前系统的账号进行绑定
      /*  try {
            String nickName = getNickName(unionid);
            if(!"".equals(nickName)){
                //绑定成功
                req.setAttribute("nickName", nickName);
                req.getRequestDispatcher("/index2.jsp").forward(req, resp);
            }else{
                //未绑定
                req.setAttribute("unionid", unionid);
                req.getRequestDispatcher("/login.jsp").forward(req, resp);
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }*/
    }

//    public String getNickName(String unionid) throws SQLException{
//        String nickName = "";
//        conn = DriverManager.getConnection(dbUrl, userName, passWord);
//        String sql = "select nickname from user where unionid=?";
//        ps = conn.prepareStatement(sql);
//        ps.setString(1, unionid);
//        rs = ps.executeQuery();
//        while(rs.next()){
//            nickName = rs.getString("NICKNAME");
//        }
//        rs.close();
//        ps.close();
//        conn.close();
//        return nickName;
//    }
//
//    public int updUser(String unionid,String account,String password) throws SQLException{
//        conn = DriverManager.getConnection(dbUrl, userName, passWord);
//        String sql = "update user set unionid=? where account=? and password=?";
//        ps = conn.prepareStatement(sql);
//        ps.setString(1, unionid);
//        ps.setString(2, account);
//        ps.setString(3, password);
//        int temp = ps.executeUpdate();
//
//        rs.close();
//        ps.close();
//        conn.close();
//        return temp;
//    }
//
//    @Override
//    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
//            throws ServletException, IOException {
//        String account = req.getParameter("account");
//        String password = req.getParameter("password");
//        String unionid = req.getParameter("unionid");
//        try {
//            int temp = updUser(unionid, account, password);
//            if(temp>0){
//                System.out.println("账号绑定成功");
//            }else{
//                System.out.println("账号绑定失败");
//            }
//        } catch (SQLException e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        }
//
//    }
}
